package com.vipbbo.security.springboot.service;

import com.vipbbo.security.springboot.dao.UserDao;
import com.vipbbo.security.springboot.model.UserDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author bbo(zbw)
 * Description 自定义UserDetailsService
 * @Date 2021/4/22
 */

@Service
public class SpringDataUserDetailsService implements UserDetailsService {

    @Autowired
    UserDao userDao;
    // 根据账号查询用户信息
    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {

        // 将来连接数据库查询....
        UserDto userDto = userDao.getUserByUsername(userName);
        if (userDto ==null){
            // 如果用户查不到 返回null 由provider来抛异常
            return null;
        }
        /*
        // 这里暂时使用静态数据
        // 登录账号
        System.out.println("userName:"+userName);

        // 这里暂时使用静态数据
        UserDetails userDetails = User.withUsername("zhangsan").password("$2a$10$znTniIv/w7bUfdtofe7.c.GM0TW9CvCO/BrOfvVDayxuHSFdPhJi2").authorities("p1").build();
        return userDetails;
        */
        /*
        // 用户信息从数据查询 但是权限也是写死的
        UserDetails userDetails = User.withUsername(userDto.getUsername()).password(userDto.getPassword()).authorities("p1").build();
        return userDetails;
        */

        // 根据用户id查询用户的权限
        List<String> permissions = userDao.findPermissionsByUserId(userDto.getId());
        // 将permissions转成数组
        String[] permissionArray = new String[permissions.size()];
        permissions.toArray(permissionArray);
        UserDetails userDetails = User.withUsername(userDto.getUsername()).password(userDto.getPassword()).authorities(permissionArray).build();
        return userDetails;

    }
}
